'use strict';

/**
 * 部门服务
 */
const Service = require('egg').Service;

class DepartmentService extends Service {
  /**
   * 创建部门
   * @param {Object} deptData - 部门数据
   * @return {Promise<Object>} 创建的部门
   */
  async create(deptData) {
    const { ctx } = this;
    // 检查部门名称是否已存在
    const existDept = await ctx.model.Department.findOne({ name: deptData.name });
    if (existDept.name === deptData.name) {
      ctx.throw(400, '部门名称已存在');
    }

    // 处理parentId字段，确保空字符串转换为默认值0
    if (deptData.parentId === '' || deptData.parentId === null || deptData.parentId === undefined) {
      deptData.parentId = 0;
    }

    return ctx.model.Department.create(deptData);
  }

  /**
   * 查询部门列表
   * @param {Object} query - 查询条件
   * @param {Number} page - 页码
   * @param {Number} pageSize - 每页数量
   * @return {Promise<Object>} 部门列表和总数
   */
  async list(query = {}, page = 1, pageSize = 10) {
    const { ctx } = this;
    const offset = (page - 1) * pageSize;
    const where = {};

    if (query.name) {
      where.name = { [ctx.Sequelize.Op.like]: `%${query.name}%` };
    }

    if (query.status !== undefined && query.status !== '') {
      where.status = query.status;
    }

    if (query.parentId !== undefined && query.parentId !== '') {
      where.parentId = query.parentId;
    }

    const { count, rows } = await ctx.model.Department.findAndCountAll({
      where,
      offset,
      limit: pageSize,
      order: [[ 'sort', 'ASC' ], [ 'create_time', 'DESC' ]],
    });

    return {
      list: rows,
      total: count,
      page,
      pageSize,
    };
  }

  /**
   * 查询部门树
   * @param {Object} query - 查询条件
   * @return {Promise<Array>} 部门树结构
   */
  async tree(query = {}) {

    const { ctx } = this;
    const where = {};

    if (query.status !== undefined) {
      where.status = query.status;
    }

    const departments = await ctx.model.Department.findAll({
      where,
      order: [[ 'sort', 'ASC' ]],
    });

    // 构建树结构
    const buildTree = (data, parentId = 0) => {
      return data
        .filter(item => item.parentId === parentId)
        .map(item => {
          const children = buildTree(data, item.id);
          return {
            ...item.toJSON(),
            children: children.length > 0 ? children : null,
          };
        });
    };

    return buildTree(departments);
  }

  /**
   * 查询单个部门
   * @param {string} id - 部门ID
   * @return {Promise<Object>} 部门信息
   */
  async findById(id) {
    const { ctx } = this;

    return ctx.model.Department.findByPk(id);
  }

  /**
   * 更新部门
   * @param {string} id - 部门ID
   * @param {Object} deptData - 更新的部门数据
   * @return {Promise<Object>} 更新后的部门
   */
  async update(id, deptData) {
    const { ctx } = this;

    const department = await this.findById(id);
    if (!department) {
      ctx.throw(404, '部门不存在');
    }

    return department.update(deptData);
  }

  /**
   * 删除部门
   * @param {string} id - 部门ID
   * @return {Promise<Boolean>} 是否删除成功
   */
  async destroy(id) {
    const { ctx } = this;

    const department = await this.findById(id);
    if (!department) {
      ctx.throw(404, '部门不存在');
    }

    // 检查是否有子部门
    const children = await ctx.model.Department.count({
      where: { parentId: id },
    });

    if (children > 0) {
      ctx.throw(400, '该部门存在子部门，无法删除');
    }

    // 检查是否有用户
    const users = await ctx.model.User.count({
      where: { departmentId: id },
    });

    if (users > 0) {
      ctx.throw(400, '该部门存在用户，无法删除');
    }

    return department.destroy();
  }

  /**
   * 更新部门状态
   * @param {string} id - 部门ID
   * @param {boolean} status - 状态
   * @return {Promise<Object>} 更新后的部门
   */
  async updateStatus(id, status) {
    const { ctx } = this;

    const department = await this.findById(id);
    if (!department) {
      ctx.throw(404, '部门不存在');
    }

    department.status = status;
    return department.save();
  }
}

module.exports = DepartmentService;
